package com.right.near.common.advice;

import com.right.near.common.constants.SecurityConstants;
import com.right.near.common.exception.BusinessException;
import com.right.near.common.model.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author star
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionAdvice {

    @Value(value = "${right.near.error.message:服务器开小差了}")
    private String errMessage;

    /**
     * all exception handling
     *
     * @param e abnormal information
     * @return ResponseEntity ResponseEntity ResponseVO
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseVO<Object>> handleBindException(Exception e) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");

        ResponseVO<Object> response = new ResponseVO<>();
        HttpStatus httpStatus = HttpStatus.OK;
        log.error("Exception", e);
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setMessage(businessException.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
            String message = fieldErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(", "));
            response.setCode(HttpStatus.BAD_REQUEST.value());
            response.setMessage(message);
        } else if (e instanceof AccessDeniedException) {
            response.setCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value());
            response.setMessage(SecurityConstants.FORBIDDEN);
        } else {
            response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setMessage(errMessage.trim());
        }
        return new ResponseEntity<>(response, headers, httpStatus);
    }

}
